package com.stox.core.ui.swing.util;

import javax.swing.JOptionPane;

import com.stox.core.ui.swing.widget.MainFrame;
import com.stox.core.util.Constant;
import com.stox.core.util.StringUtil;

public class ThrowableReporter {

	public static void report(Throwable e) {
		e.printStackTrace();
		JOptionPane.showMessageDialog(MainFrame.getInstance(),
				getExceptionMessage(getRootThrowable(e)), "Error", JOptionPane.ERROR_MESSAGE);
	}

	public static void report(String message) {
		JOptionPane.showMessageDialog(MainFrame.getInstance(),message, "Error", JOptionPane.ERROR_MESSAGE);
	}

	
	public static String getExceptionMessage(Throwable t) {
		if (StringUtil.hasText(t.getMessage())) {
			return t.getMessage();
		} else {
			StackTraceElement[] ste = t.getStackTrace();
			if (ste != null && ste.length > 0) {
				StackTraceElement elem = ste[0];
				return "Throwable : " + t.getClass().getSimpleName() + Constant.lineSeparator
						+ "File : " + elem.getFileName()+ Constant.lineSeparator 
						+ "Class : "+ elem.getClassName() + Constant.lineSeparator
						+ "Method : " + elem.getMethodName()+ Constant.lineSeparator 
						+ "Line : "+ elem.getLineNumber() + Constant.lineSeparator;
			}
		}
		return "";
	}

	public static Throwable getRootThrowable(Throwable t) {
		Throwable cause = t.getCause();
		if (cause != null) {
			return getRootThrowable(t.getCause());
		} else {
			return t;
		}
	}

}
